package com.ys.peony.ui.activity;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ys.peony.R;
import com.ys.peony.app.HttpURL;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.BaseActivity;
import com.ys.peony.enums.BusinessDetailStatus;
import com.ys.peony.enums.SwipeDirect;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.model.CarModel;
import com.ys.peony.model.JiekuanrenModel;
import com.ys.peony.model.MessageDetailModel;
import com.ys.peony.model.MessageModel;
import com.ys.peony.model.MessageResponse;
import com.ys.peony.model.UserModel;
import com.ys.peony.ui.widget.Divider;
import com.ys.peony.utils.DateUtils;
import com.ys.peony.utils.JSONUtil;
import com.ys.peony.utils.LoadingProgressUtils;
import com.ys.peony.utils.NetUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.StringUtils;
import com.ys.peony.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import com.yklab.library.refreshlayout.adapters.CommonRecyclerViewAdapter;
import com.yklab.library.refreshlayout.holder.CommonRecyclerViewHolder;
import com.yklab.library.refreshlayout.listener.OnTouchListenerLoadAction;

/**
 * describe:消息
 * author:zhangcong
 * date:2017/6/11 14:24
 */
public class MessageActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R.id.view_blank)
    LinearLayout view_blank;

    private CommonRecyclerViewAdapter mAdapter;
    private List<MessageDetailModel> mList;
    private LinearLayoutManager mLayoutManager;

    private boolean isLoadAction = false;
    private boolean isLoading = false;
    private int lastVisiableItem = 1;
    //动作类型
    private int actionType = YSConstant.INVALID;


    @Override
    protected int getContentResId() {
        return R.layout.activity_message;
    }

    @Override
    protected void initView() {
        initData();
        setListener();
        setAdapter();
        onRefresh();
    }

    private void initData() {
        mList = new ArrayList<>();
        mLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
        mAdapter = new CommonRecyclerViewAdapter<MessageDetailModel>(this, mList, R.layout.message_detail_item) {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {
                super.onBindViewHolder(holder, position);
                if (!isFooterView(position)) {
                    MessageDetailModel model = mList.get(position);
                    if (model != null) {
                        ((CommonRecyclerViewHolder) holder)
                                .setText(R.id.tv_message_content, model.getContext())
                                .setText(R.id.tv_date, DateUtils.parseDateTime(model.getSend_time()));
                    }
                }
            }
        };
        mAdapter.isHasFooter(true);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE &&
                        lastVisiableItem + 1 >= mAdapter.getItemCount()) {
                    if (!isLoading && isLoadAction) {
                        changeLoading(true);
                        currentPage++;
                        actionType = YSConstant.ACTION_TYPE_UP;
                        getData();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisiableItem = mLayoutManager.findLastVisibleItemPosition();
            }
        });

    }

    private void setAdapter() {
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void setListener() {
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.textGreen));
        //上拉行为监听
        mRecyclerView.setOnTouchListener(new OnTouchListenerLoadAction() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                isLoadAction = super.onTouch(view, motionEvent);
                return false;
            }
        });
    }

    /**
     * describe:查看站内信
     * author:czhang
     * date:2017/6/11 19:56
     */
    private void getData() {
        UserModel userModel = SharePreferencesUtils.getInstance().getUserModel();
        if (null == userModel) {
            ToastUtils.showToast("用户信息为空");
            return;
        }
        if (!NetUtils.isNetworkConnected(this)) {
            ToastUtils.showToast(getResources().getString(R.string.no_net_error));
            return;
        }
        final JCHttpManagerUtils httpManagerUtils = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", Long.parseLong(userModel.getId()));
        params.put("currentPage", currentPage);
        params.put("pageNum", pageNum);
        httpManagerUtils.getNoEncrypt(HttpURL.getMessagesForMobile, params, new BaseRespCallBack() {
            @Override
            public void onRespSuccess(String respStr) {
                final MessageResponse messageResponse = JSONUtil.parseObject(respStr, MessageResponse.class);
                setData(messageResponse.getData());
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                dismissFresh();
                changeLoading(false);
            }
        });
    }

    private void setData(final MessageModel messageModel) {
        switch (actionType) {
            case YSConstant.ACTION_TYPE_UP://上拉
                changeLoading(false);
                if (messageModel != null && messageModel.getDataList() != null) {
                    final int size = mList.size();
                    mList.addAll((messageModel.getDataList()));
                    mAdapter.notifyItemRangeInserted(size, mList.size());
                }
                break;
            case YSConstant.ACTION_TYPE_DOWN://下拉刷新
                dismissFresh();
                if (messageModel != null && messageModel.getDataList() != null) {
                    mList.clear();
                    mList.addAll(messageModel.getDataList());
                    mAdapter.notifyDataSetChanged();
                    if (messageModel.getDataList().size() < 1) {
                        showBlankView();
                    } else {
                        hideBlankView();
                    }
                } else {
                    showBlankView();
                }
                break;
        }
    }

    @Override
    public void onRefresh() {
        currentPage = 0;
        actionType = YSConstant.ACTION_TYPE_DOWN;
        getData();
    }

    private void dismissFresh() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    private void changeLoading(boolean loading) {
        if (mAdapter != null) {
            isLoading = loading;
            mAdapter.setLoadingStatus(loading);
        }
    }

    private void showBlankView() {
        view_blank.setVisibility(View.VISIBLE);
        mSwipeRefreshLayout.setVisibility(View.GONE);
    }

    private void hideBlankView() {
        view_blank.setVisibility(View.GONE);
        mSwipeRefreshLayout.setVisibility(View.VISIBLE);
    }
}
